/*
 * Copyright 2007 Ulf Ochsenfahrt <ulf@ofahrt.de>
 *
 * This file is part of mnemoj, a software transactional memory implementation
 * that is based on Project Darkstar.
 *
 * mnemoj is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation and
 * distributed hereunder to you.
 *
 * Project Darkstar Server is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.ofahrt.mnemoj.impl;

import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.Task;
import com.sun.sgs.app.TaskManager;
import com.sun.sgs.app.TransactionNotActiveException;

public final class AppContextDispatcher
{

private static final ThreadLocal<ManagerContext> threadContexts = new ThreadLocal<ManagerContext>();

static void call(ManagerContext context, Task task)
{
	if (threadContexts.get() != null) throw new IllegalStateException();
	boolean done = false;
	try
	{
		threadContexts.set(context);
		task.run();
		done = true;
	}
	finally
	{
		threadContexts.set(null);
		if (done)
			context.getTaskTransaction().commit();
		else
			context.getTaskTransaction().revert();
	}
}

static Transaction getTaskTransaction()
{
	ManagerContext context = threadContexts.get();
	if (context == null) throw new TransactionNotActiveException("");
	return context.getTaskTransaction();
}

public static DataManager getDataManager()
{
	return threadContexts.get().getDataManager();
}

public static TaskManager getTaskManager()
{
	return threadContexts.get().getTaskManager();
}

}
